<template>
  <div>
    <div class="radius-container">
      <div class="border-b pad-10 font-w font-15 topbar-style">基本设置</div>
      <div class="pad-20">
        <el-form :model="share" label-width="100px" :rules="rules" ref="share">
          <div class="flex v-align-c gray-bar">
            <el-form-item label="分发酬金：" class="input-bar-1" prop="amount" >
              <el-input v-model="share.amount" placeholder="请输入您的酬金预算" min="0" class="width-input-1" @change="budgetAmountChange"></el-input>
            </el-form-item>
            <el-form-item label="阅读量：" class="input-bar-2" prop="targetReading">
              <el-input v-model="share.targetReading" placeholder="请输入数量" min="1" class="width-input-3" @change="targetReadingChange"></el-input>
              单价：<span class="pad-l-5 pad-r-5">{{ share.unitPrice }}</span> 元/个阅读量
              剩余：<span class="pad-l-5 pad-r-5">{{ balance }}</span>元
            </el-form-item>
          </div>

          <el-form-item label="分发周期：">
            <el-switch v-model="internalRatioFlag"></el-switch>
            <template v-if="internalRatioFlag">
              <el-date-picker
                v-model="starEndTime"
                type="daterange"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="分发开始日期"
                end-placeholder="分发结束日期">
              </el-date-picker>
              <br/><span style="margin-left: 50px; font-size: 8px">分发开始时间:未到开始时间微客无法收到分发任务推送</span>
              <br/><span style="margin-left: 50px; font-size: 8px">分发结束时间:在达到分发结束时间后,微客分发将无法获得酬金,剩余的酬金将退回到账户余额中</span>
            </template>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="radius-container" v-if="isShow =='1'">
      <div class="border-b pad-10 font-w font-15 topbar-style">微客要求</div>
        <div class="pad-20">
          <el-form :model="form" label-width="135px" :rules="rules">
            <div class="flex v-align-c">
              <el-switch v-model="form.cooperationFlag" class="mar-l-20"></el-switch>
              <el-form-item label="筛选合作的微客：" class="mar-b-0">
                <div class="flex">
                  <el-popover
                    placement="top-start"
                    title="说明"
                    width="200"
                    trigger="hover"
                    class="mar-l--10 pad-r-15"
                    content="选择推送范围：根据你的选择把任务推送给你选择的微客类型；定向选择微客：任务只推送给你选择的微客">
                    <svg-icon slot="reference" class="questionCircle mar-t-8" icon-class="questionCircle" />
                  </el-popover>
                  <el-form-item label="" v-if="form.cooperationFlag">
                    <el-radio-group v-model="form.cooperationFilterType">
                      <template v-for="type in cooperationFilterTypeTypes">
                        <el-radio :label="type.key">{{type.value}}</el-radio>
                      </template>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-form-item>
            </div>
            <el-row v-if="form.cooperationFlag">
              <el-form-item label-width="195px" label="" v-if="form.cooperationFilterType==1">
                <el-radio-group v-model="form.filterDirectionType" class="pad-l-25">
                  <template v-for="type in filterDirectionTypeTypes">
                    <el-radio :label="type.key">{{type.value}}</el-radio>
                    <!-- 1：只推送公共微客 -->
                    <el-popover v-if="type.key == 0"
                      placement="top-start"
                      title="说明"
                      width="200"
                      trigger="hover"
                      class="pad-l-5 pad-r-25"
                      content="项目只推给公共微客">
                    <svg-icon slot="reference" class="questionCircle" icon-class="questionCircle" />
                    </el-popover>
                    <!-- 1：只推送外部微客 -->
                    <el-popover v-if="type.key == 1"
                      placement="top-start"
                      title="说明"
                      width="200"
                      trigger="hover"
                      class="pad-l-5 pad-r-25"
                      content="项目只推给公司招募员招募的，且有绑定关系的微客">
                    <svg-icon slot="reference" class="questionCircle" icon-class="questionCircle" />
                    </el-popover>
                    <!-- popover提示框 结束 -->
                    <!-- 2：只推送内部微客  -->
                    <el-popover v-if="type.key == 2"
                      placement="top-start"
                      title="说明"
                      width="200"
                      trigger="hover"
                      class="pad-l-5 pad-r-25"
                      content="项目只推给公司内部在职的内部创客。">
                      <svg-icon slot="reference" class="questionCircle" icon-class="questionCircle" />
                    </el-popover>
                    <!-- popover提示框 结束 -->
                    <!-- 2：只推送内部微客  -->
                    <el-popover v-if="type.key == 3"
                      placement="top-start"
                      title="说明" width="200"
                      trigger="hover"
                      class="pad-l-5 pad-r-25"
                      content="项目将推给公司的内部创客，和招募员招募且有绑定关系的微客">
                      <svg-icon slot="reference" class="questionCircle" icon-class="questionCircle" />
                    </el-popover>
                    <!-- popover提示框 结束 -->
                  </template>
                </el-radio-group>
              </el-form-item>
            </el-row>

            <el-row v-if="form.cooperationFlag">
              <el-col :span="24">
                <el-form-item label-width="195px" label="选择推送：" v-if="form.cooperationFilterType==2">
                  <el-input type="textarea" :rows="5"
                    placeholder="请输入内容" class="pad-t-12 pad-l-25"
                    style="width: 50%" v-model="selectPushMemberNames"/>
                  <el-button type="primary" size="mini" class="mar-l-15" @click="selectPushMember()">选择微客</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="flex v-align-c flex-area" :class="form.recruitFlag?'area-height':''">
              <el-switch v-model="form.recruitFlag" class="mar-l-20"></el-switch>
              <el-form-item label="是否招募新微客：" class="mar-b-0">
                <div class="flex v-align-c mar-t--3">
                  <div class="pad-t-5 mar-l--15 mar-r--10">
                    <el-popover
                      placement="top-start"
                      title="说明："
                      width="200"
                      trigger="hover"
                      class="pad-l-5 pad-r-25"
                      content="选择招募后，公司相关的招募员将收到招募海报信息。不选择招募后，公司招募员将不会收到招募海报信息。">
                      <svg-icon slot="reference" class="questionCircle inline-block" icon-class="questionCircle" />
                    </el-popover>
                  </div>
                </div>
                </el-form-item>
                <div v-if="form.recruitFlag" class="area-box">
                  <el-input type="textarea" :rows="3" placeholder="请输入内容"  style="width: 38%" v-model="selectRecruiterNames"/>
                  <el-button type="primary" size="mini" class="mar-l-15" @click="selectRecruiter">选择招募员</el-button>
                </div>
            </div>
        </el-form>
      </div>
    </div>
    <!-- 选择招募微客 -->
    <div>
      <el-dialog width="700px"  v-el-drag-dialog :visible.sync="recruiterDialog" center >
        <div class="flex pad-l-30 mar-t-30">
          <div class="mar-l-5">
            <el-transfer
              style="text-align: left; display: inline-block"
              v-model="recruiterValues"
              filterable
              :left-default-checked="[]"
              :right-default-checked="recruiterRightValues"
              :titles="['备选项', '已选择']"
              :button-texts="['去除', '添加']"
              :format="{
                  noChecked: '${total}',
                  hasChecked: '${checked}/${total}'
                }"
              :data="recruiterDatas">
            </el-transfer>
          </div><br/>
        </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeRecruiter">取消</el-button>
            <el-button type="primary" @click="submitRecruiter">确定</el-button>
          </div>
      </el-dialog>
    </div>

    <div>
      <el-dialog width="700px"  v-el-drag-dialog :visible.sync="pushMemberDialog" center >
        <div class="flex pad-l-30 mar-t-30">
          <div class="mar-l-5">
            <el-transfer
              style="text-align: left; display: inline-block"
              v-model="pushMemberValues"
              filterable
              :left-default-checked="[]"
              :right-default-checked="pushMemberRightValues"
              :titles="['备选项', '已选择']"
              :button-texts="['去除', '添加']"
              :format="{
                  noChecked: '${total}',
                  hasChecked: '${checked}/${total}'
                }"
              :data="pushMemberDatas">
            </el-transfer>
          </div>
            <br>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closePushMember">取消</el-button>
          <el-button type="primary" @click="submitPushMember">确定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="radius-container">
      <div class="border-b pad-10 font-w font-15 topbar-style">结算方式</div>
      <div class="pad-20">
        结算方式：
        <template>
          <el-radio v-model="settleType" label="1">点开阅读扣费</el-radio>
          <el-radio v-model="settleType" label="2">提交表单扣费</el-radio>
        </template>
      </div>
    </div>

    <div slot="footer" class="radius-container dialog-footer pad-t-30 pad-b-30">
      <el-button @click="that.$router.go(-1)">返回</el-button>
      <el-button type="danger" @click="saveData">立即发布</el-button>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .flex-area{
    position: relative;
  .area-box{
    position: absolute;
    width: 100%;
    left: 218px;
    top: 10px;
  }
  }
  .area-height{
    padding-bottom: 60px;
  }
  .flag-box{
    padding-left: 70px;
  }
  .el-input{
    width:20%
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .main-transfer {
    width: 200px;
  }

  .main-transfer-title {
    background-color: #f5f7fa;
    height: 40px;
    font-size: 16px;
    padding-left: 20px;
  }

  .main-transfer-list {
    height: 260px;
    overflow-y: scroll;
  }
  .input-bar-1{
    width: 40%;
    margin-bottom: 5px!important;
  }
  .input-bar-2{
    width: 60%;
    margin-bottom: 5px!important;
  }
  .width-input-1{
    width: 100%!important;
  }
  .width-input-3{
    width: 30%!important;
  }
  .gray-bar{
    background: #f2f2f2;
    padding: 5px 0 0 0;
    margin-bottom: 20px;
  }
</style>

<script>
  import { getDictByGroupName } from '@/api/common/common'
  import { listRecruiterList, listPushMemberList } from '@/api/project/taskInfo'
  import { saveShare } from '@/api/content/share'
  import { dealDict } from '@/utils/select'
  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  export default {
    directives: {
      // 拖动窗口
      elDragDialog
    },
    props: {
      // 分发文章id
      articleId: {
        type: String
      },
      // 分发id
      contentId: {
        type: String
      }
    },
    data() {
      return {
        starEndTime: [],
        settleType: '1',
        that: this,
        internalRatioFlag: false,
        balance: 0,
        share: {
          contentId: '',
          contentCode: '',
          contentName: '',
          targetReading: 1,
          surplusTargetReading: 1,
          createTime: '',
          updateTime: '',
          status: '',
          settleType: '',
          amount: '',
          unitPrice: '',
          startTime: '',
          endTime: '',
          articleId: this.articleId,
          enterpriseId: this.getEnterpriseId(),
          contentShelf: '',
          // 定向选择微客集合
          memberIds: [],
          // 招募员集合
          recruiterIds: []
        },
        // 内容分发微客要求
        shareMemberRequire: {
          cooperationFlag: '',
          cooperationFilterType: '',
          recruitFlag: '',
          filterDirectionType: ''
        },
        form: {
          cooperationFlagType: '0',
          cooperationFilterType: '1',
          experienceIds: [],
          skillIds: [],
          bargainingFlagMap: {}, // ????
          filterDirectionType: '0',
          recruitFlagType: '0',
          cooperationFlag: false,
          recruitFlag: false
        },
        hireNum: '',
        payDay1: '',
        payDay2: '',

        cooperationFilterTypeTypes: [],
        cooperationFilterTypeMap: {},
        // 是否启用合作微客
        cooperationFlagTypeTypes: [],
        cooperationFlagTypeMap: {},
        filterDirectionTypeTypes: [],
        filterDirectionTypeMap: {},
        // 招募弹窗 Id
        recruiterDialog: false,
        // 所选类目集合
        recruiterValues: [],
        // 右侧选中
        recruiterRightValues: [],
        // 招募员集合
        recruiterDatas: [],
        // 选择的招募员Id
        selectRecruiterIds: [],
        // 招募员Map
        recruiterMap: new Map(),
        // 使用的名称集合
        selectRecruiterNames: '',
        // 招募员Id集合
        recruitMemberIds: [],
        // 招募弹窗 Id
        pushMemberDialog: false,
        // 所选类目集合
        pushMemberValues: [],
        // 右侧选中
        pushMemberRightValues: [],
        // 选择推送微客集合
        pushMemberDatas: [],
        // 选择推送微客Id
        selectPushMemberIds: [],
        // 选择推送微客Map
        pushMemberMap: new Map(),
        // 微客使用的名称集合
        selectPushMemberNames: '',
        // 微客Id集合
        pushMemberIds: [],
        rules: {
          amount: [
            { required: true, message: '请输入预算金额', trigger: 'blur' },
            { pattern: /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/, message: '请输入正确金额' }
          ],
          targetReading: [
            { required: true, message: '请输入阅读量', trigger: 'blur' },
            { pattern: /^\+?[1-9]\d*$/, message: '请输入大于0的整书' }
          ]
        },
        isShow: '1'
      }
    },
    // 初始化页面
    created() {
      this.initDict()
    },
    mounted() {
      // 初始化数据
      this.initlistRecruiterList()
      this.initListPushMemberList()
    },
    methods: {
      initDict() {
        getDictByGroupName('ShareDTO').then(response => {
          // 动态生成字典放入集合中
          const dictObj = dealDict(response.data)
          Object.keys(dictObj).forEach(key => {
            this[key + ''] = dictObj[key + '']
          })
          // 动态生成字典Map,页面显示使用
          Object.keys(response.data).forEach((name) => {
            const key = name + 'Map'
            const value = response.data[name]
            this[key] = value
          })
        })
      },
      resetShare() {
        this.share = {
          contentId: '',
          contentCode: '',
          contentName: '',
          targetReading: 1,
          createTime: '',
          updateTime: '',
          status: '',
          settleType: '',
          contentArticle_id: '',
          amount: '',
          unitPrice: '',
          startTime: '',
          endTime: '',
          enterpriseId: '',
          delFlag: '',
          contentShelf: ''
        }
      },
      // 选择招募员
      selectRecruiter() {
        this.recruiterDialog = true
      },
      // 启动招募微客
      changeRecruitFlagType(val) {
        this.form.recruitFlagType = val
      },
      // 选择招募新微客
      submitRecruiter() {
        const recruiterValues = this.recruiterValues
        this.selectRecruiterIds = recruiterValues
        const recruiterMap = this.recruiterMap
        const recruiterNamesArray = []
        const recruitMemberIds = []
        recruiterValues.forEach(recruiterId => {
          const recruiter = recruiterMap.get(recruiterId)
          const username = recruiter.username
          recruiterNamesArray.push(username)
          recruitMemberIds.push(recruiterId)
        })

        const selectRecruiterNames = recruiterNamesArray.join(';')
        this.selectRecruiterNames = selectRecruiterNames
        //   recruitMemeberIds
        this.recruitMemberIds = recruitMemberIds
        this.recruiterDialog = false
      },
      // 加载招募员
      initlistRecruiterList() {
        const enterpriseId = this.getEnterpriseId()
        listRecruiterList(enterpriseId).then(response => {
          const array = response.data
          const data = []

          const recruiterMap = new Map()
          array.forEach((recruiter) => {
            data.push({
              label: recruiter.realname,
              key: recruiter.recruiterId
            })
            recruiterMap.set(recruiter.recruiterId, recruiter)
          })
          this.recruiterDatas = data
          this.recruiterMap = recruiterMap
        })
      },
      closeRecruiter() {
        this.recruiterDialog = false
      },
      closePushMember() {
        this.pushMemberDialog = false
      },
      submitPushMember() {
        const pushMemberValues = this.pushMemberValues
        this.selectPushMemberIds = pushMemberValues
        const pushMemberMap = this.pushMemberMap
        const pushMemberNamesArray = []
        const pushMemberIds = []
        pushMemberValues.forEach(pushMemberId => {
          const pushMember = pushMemberMap.get(pushMemberId)
          const nickname = pushMember.nickname
          pushMemberNamesArray.push(nickname)
          pushMemberIds.push(pushMemberId)
        })

        const selectPushMemberNames = pushMemberNamesArray.join(';')
        this.selectPushMemberNames = selectPushMemberNames
        this.pushMemberIds = pushMemberIds
        this.pushMemberDialog = false
      },
      changePushMemberType(type) {
        if (type === 1) {
          this.pushMemberType = 0
        } else {
          this.pushMemberType = 1
        }
      },
      selectPushMember() {
        this.pushMemberDialog = true
      },
      // 初始化微客
      initListPushMemberList() {
        listPushMemberList(this.getEnterpriseId()).then(response => {
          const array = response.data
          const data = []
          const pushMemberMap = new Map()

          array.forEach((pushMember) => {
            data.push({
              label: pushMember.nickname,
              key: pushMember.memberId
            })
            pushMemberMap.set(pushMember.memberId, pushMember)
          })
          this.pushMemberDatas = data
          this.pushMemberMap = pushMemberMap
        })
      },
      budgetAmountChange() {
        const patt = new RegExp(/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/)
        const result = patt.test(this.share.amount)
        if (!result) {
          this.share.amount = ''
        } else {
          if (this.share.targetReading > 0) {
            const amount = Math.floor(this.share.amount / this.share.targetReading * 100) / 100
            if (amount >= 0.01) {
              this.share.unitPrice = amount
              this.balance = (this.share.amount * 100 - Math.floor(this.share.unitPrice * this.share.targetReading * 100)) / 100
            } else {
              this.share.amount = ''
              this.$message({
                type: 'error',
                message: '阅读单价必须大于0.01元'
              })
            }
          }
        }
      },
      targetReadingChange() {
        const patt = new RegExp(/^\+?[1-9]\d*$/)
        const result = patt.test(this.share.targetReading)
        if (!result) {
          this.share.targetReading = ''
        } else {
          if (this.share.amount > 0) {
            const amount = Math.floor(this.share.amount / this.share.targetReading * 100) / 100
            if (amount >= 0.01) {
              this.share.unitPrice = amount
              this.balance = (this.share.amount * 100 - Math.floor(this.share.unitPrice * this.share.targetReading * 100)) / 100
            } else {
              this.share.targetReading = ''
              this.$message({
                type: 'error',
                message: '阅读单价必须大于0.01元'
              })
            }
          }
        }
      },
      saveData() {
        this.$refs['share'].validate((valid) => {
          if (valid) {
            if (!this.form.cooperationFlag && !this.form.recruitFlag) {
              this.$message({
                type: 'error',
                message: '请至少选择一个微客要求'
              })
              return
            }
            if (this.internalRatioFlag) {
              if (this.starEndTime && this.starEndTime.length === 0) {
                this.$message({
                  type: 'error',
                  message: '请选择分发周期,或者关闭分发周期'
                })
                return
              }
            }
            // 分发周期添加
            if (this.internalRatioFlag) {
              const time = Date.parse(new Date())
              if ((Date.parse(this.starEndTime[0]) + 86400000) < time) {
                this.$message({
                  type: 'error',
                  message: '开始时间不能小于当前时间!'
                })
                this.starEndTime = []
                return
              }
              this.share.startTime = this.starEndTime[0] + ' 00:00:00'
              this.share.endTime = this.starEndTime[1] + ' 23:59:59'
            }
            // 筛选合作的微客
            if (this.form.cooperationFlag) {
              this.shareMemberRequire.cooperationFlag = 1
              this.shareMemberRequire.cooperationFilterType = this.form.cooperationFilterType

              if (this.form.cooperationFilterType === '1') {
                // 选择推送范围
                this.shareMemberRequire.filterDirectionType = this.form.filterDirectionType
              } else {
                // 定向选择
                if (this.selectPushMemberIds.length === 0) {
                  this.$message({
                    type: 'error',
                    message: '请选择微客!'
                  })
                  return
                }
                this.share.memberIds = this.selectPushMemberIds
              }
            } else {
              this.shareMemberRequire.cooperationFlag = 0
            }
            // 是否招募新微客
            if (this.form.recruitFlag) {
              // 是否招募新微客 recruitFlag
              this.shareMemberRequire.recruitFlag = 1
              if (this.selectRecruiterIds.length === 0) {
                this.$message({
                  type: 'error',
                  message: '请选择招募微客!'
                })
                return
              }
              this.share.recruiterIds = this.selectRecruiterIds
            } else {
              this.shareMemberRequire.recruitFlag = 0
            }
            this.share.shareMemberRequire = this.shareMemberRequire
            this.share.settleType = this.settleType
            // 保存
            saveShare(this.share).then(response => {
              if (response.isError) return
              this.$message({
                type: 'success',
                message: '成功!'
              })
              this.$router.push({ path: '/content/share/index' })
            })
          }
        })
      }
    }
  }
</script>
